<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="view-table">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formshow">
          <template #SpuCategory>
            <SelectProductCategories filterable multiple collapse-tags slotType="cascader" style="width: 200px" v-model:modelValue="form['spu_category']" placeholder="产品分类" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="openBindSiteCountry">站点可发货国家配置</el-button>
        <el-button type="primary" @click="openConfirmInput('salesStatus', false)">批量标记状态</el-button>
        <el-button type="primary" @click="openDialogDetectionConfig">可售数量调0配置</el-button>   

        <el-button class="ml-auto" @click="openDialogImport('price')">批量维护供货价</el-button>
        <el-button @click="openDialogImport('sku')">维护链接可售数量</el-button>

        <el-button @click="importHandleClick">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button>
      </template>

      <template #soltHeaderTransit="{ column }">
        <div class="flex items-center" v-for="item in transitHeader" :key="item.title">
          <div>{{ item.title }}</div>
          <div class="ml-[8px]"></div>
        </div>
      </template>
      <template #soltHeader="{ column }">
        <div class="flex items-center">
          <div class="mr-[8px]">{{ column.title }}</div>

          <el-dropdown trigger="click">
            <span class="el-dropdown-link text-[#3487ff]">
              排序
              <div class="dk-iconfont icon-ArrowDown"></div>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- asc：升序；desc：降序 -->
                <div class="flex items-center px-[4px] px-[2px]" v-for="item in headerMemu[column.field]" :key="item.title">
                  <div>
                    {{ item.title }}
                  </div>
                  <div class="ml-[8px] flex" style="flex-direction: column">
                    <div
                      style="font-size: 10px !important"
                      class="mb-[-4px] cursor-pointer dk-iconfont icon-CaretTop"
                      :class="item.type == 'asc' ? 'text-[#3487ff]' : 'text-[#999]'"
                      @click="tableSort(item, 'asc')"
                    ></div>

                    <div
                      style="font-size: 10px !important"
                      class="mt-[-2px] cursor-pointer dk-iconfont icon-CaretBottom"
                      :class="item.type == 'desc' ? 'text-[#3487ff]' : 'text-[#999]'"
                      @click="tableSort(item, 'desc')"
                    ></div>

                    <!-- <CaretTop style="width: 1em; height: 1em" class="mb-[-2px] cursor-pointer" :class="item.type == 'asc' ? 'text-[#3487ff]' : 'text-[#999]'" @click="tableSort(item, 'asc')" /> -->
                    <!-- <CaretBottom style="width: 1em; height: 1em" class="mt-[-2px] cursor-pointer" :class="item.type == 'desc' ? 'text-[#3487ff]' : 'text-[#999]'" @click="tableSort(item, 'desc')" /> -->
                  </div>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>

      <template #Sales="{ row }">
        <VText title="今天销量" :value="row.today_qty" line="1" class="text-green font-bold" />
        <VText title="昨天销量" :value="row.yesterday_qty" line="1" class="text-yellow font-bold" />
        <VText title="前天销量" :value="row.before_yesterday_qty" line="1" class="text-red font-bold" />
        <VText title="上前销量" :value="row.prev_before_yesterday_qty" line="1" class="text-red font-bold" />
      </template>
    </VTable>

    <VLog ref="logRef" :api="listingLog"></VLog>

    <!-- 系统可用库存 -->
    <AssembleSkuSee ref="AssembleSkuSeeRef" />

    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>

    <!-- 弹窗 表格数据展示 -->
    <DialogTableInfo v-model="dialogTableInfoVisible" v-bind="tableInfoConfirm" />

    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit">
      <!-- 修改供货价 -->
      <template #GoodsPrice v-if="currentConfirm.type == 'goodsPrice'">
        <!-- <el-input v-model="currentConfirm.form.goods_price" class="h-[32px]" placeholder="供货价" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')">
          <template #append>
            <el-select v-model="currentConfirm.form.goods_price.currency" placeholder="币种" style="width: 115px" filterable>
              <el-option v-for="item in originOption.currency" :label="item.label" :value="item.label" :key="item.label" />
            </el-select>
          </template>
        </el-input> -->
        <div>
          <el-table :data="currentConfirm.form.goods_price" border style="width: 100%">
            <el-table-column prop="platform_site_name" label="站点" width="200" />
            <el-table-column label="供货价" width="420">
              <template #header>
                供货价
                <el-popover placement="top" :width="400" trigger="click" :visible="priceForm.visible">
                  <div>
                    <el-input v-model="priceForm.goods_price" class="h-[32px]" placeholder="供货价" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')">
                      <template #append>
                        <el-select v-model="priceForm.currency" placeholder="币种" style="width: 115px" filterable>
                          <el-option v-for="item in originOption.currency" :label="item.label" :value="item.label" :key="item.label" />
                        </el-select>
                      </template>
                    </el-input>
                    <div class="text-right mt-[12px]">
                      <el-button @click="priceForm.visible = false">取消</el-button>
                      <el-button type="primary" @click="savePrice()">确认</el-button>
                    </div>
                  </div>

                  <template #reference>
                    <span class="text-[var(--el-color-primary)] cursor-pointer" @click="priceForm.visible = true">批量</span>
                  </template>
                </el-popover>
              </template>
              <template #default="{ row }">
                <el-input v-model="row.goods_price" class="h-[32px]" placeholder="供货价" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')">
                  <template #append>
                    <el-select v-model="row.currency" placeholder="币种" style="width: 115px" filterable>
                      <el-option v-for="item in originOption.currency" :label="item.label" :value="item.label" :key="item.label" />
                    </el-select>
                  </template>
                </el-input>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-[8px]">说明：根据平台规则，不同站点的供货价币种一致</div>
        </div>
      </template>
    </ConfirmInput>
    <!-- 站点可发货国家配置 -->
    <DialogoBindSiteCountry ref="DialogoBindSiteCountryRef" @refresh="query" /> 

    <!-- sku链接可售库存更新 -->
    <DialogoSkuDtock ref="DialogoSkuDtockRef" @refresh="query" />

    <!-- 批量维护供货价 -->
    <DialogImport ref="DialogImportRef" v-bind="importConfig" />

    <!-- 关联SKU -->
    <UnableAssociateSku v-model="unableSkuVisible" :rows="selectRow" @refresh="query" />

    <!-- sku链接可售库存更新 -->
    <DialogDetectionConfig ref="DialogDetectionConfigRef" :originOption="originOption" @refresh="query" />
  </VPage>
</template>

<script setup lang="jsx">
import { asinManagementList, asinManagementCreate, asinManagementEdit, asinManagementBatchUpdateField, asinManagementLog } from "@/api/base"
import { enumGet, getCountry, getShopOptions, getPlatformsSites, getGoodsSkuList, amazonSkuDetail } from "@/api"

import { getCurrency } from "@/api/public"
import { amazonListingList, listingLog, historySalesVolume, historySalesExport, ownerInventory, updateGoodsPrice } from "@/api/amazon"

import US from "@/assets/images/US.png"
import EU from "@/assets/images/EU.png"
const flag = { US, EU }

// 无法关联SKU
import UnableAssociateSku from "./components/UnableAssociateSku/index.vue"
const unableSkuVisible = ref(false)
const selectRow = ref({})
const openRelateSku = (row) => {
  if (!row.sku) {
    selectRow.value = row
    unableSkuVisible.value = true
  }
}

// 系统可用库存
import AssembleSkuSee from "./components/assembleSkuSee.vue"
const AssembleSkuSeeRef = ref()

// 站点可发货国家配置
import DialogoBindSiteCountry from "./components/DialogoBindSiteCountry.vue"
const DialogoBindSiteCountryRef = ref()
const openBindSiteCountry = () => {
  DialogoBindSiteCountryRef.value.open()
}
// sku链接可售库存更新
import DialogoSkuDtock from "./components/DialogoSkuDtock.vue"
const DialogoSkuDtockRef = ref()
const openSkuDtockRef = (row) => {
  DialogoSkuDtockRef.value.open(row)
}

const priceForm = ref({
  visible: false,
})
const savePrice = () => {
  currentConfirm.value.form?.goods_price.map((v) => {
    v.currency = priceForm.value.currency || ""
    v.goods_price = priceForm.value.goods_price || ""
  })
  priceForm.value.visible = false
}
// sku链接可售库存更新
import DialogDetectionConfig from "./components/DialogDetectionConfig.vue"
const DialogDetectionConfigRef = ref()
const openDialogDetectionConfig = () => {
  DialogDetectionConfigRef.value.open()
}

import {
  siteCountryList,
  downloaTemplate,
  goodsPriceImportCheck,
  downloadImportResult,
  goodsPriceImport,
  relateSku,
  salesStatusUpdate,
  fileTemplate,
  importImport,
  importImportCheck,
  importDownloadImportResult,
  warehouseInventoryList,
} from "./api.js"
import DialogImport from "./components/DialogImport/index.vue"
const importConfig = ref({})
const importConfigOpt = {
  // 批量维护供货价
  price: {
    templateApi: downloaTemplate, // 导入模板
    tableColumns: [
      { field: "platform_sku", title: "渠道SKU", minWidth: 150 },
      { field: "sku_code", title: "SKU货号", minWidth: 150 },
      { field: "shop", title: "店铺", width: 150 },
      { field: "platform_site", title: "平台站点", width: 150 },
      { field: "goods_price", title: "供货价", width: 150 },
      { field: "currency", title: "币种", width: 150 },
    ],
    importCheck: goodsPriceImportCheck, // 导入校验
    importResult: downloadImportResult, // 导入结果下载
    querForm: {
      platform_id: 67,
    },
    importApi: goodsPriceImport,
  },
  sku: {
    templateApi: fileTemplate, // 导入模板
    templateApiParams: { template_name: "sku链接可售导入模板" },

    tableColumns: [
      { field: "product_skc_id", title: "货品SKC ID", minWidth: 150 },
      { field: "product_sku_id", title: "货品SKU ID", width: 150 },
      { field: "sku_code", title: "SKU货号", minWidth: 150 },
      { field: "warehouse_name", title: "仓库名称", width: 150 },
      { field: "update_type", title: "编辑类型", width: 150 },
      { field: "quantity", title: "数量", width: 150 },
    ],
    importCheck: importImportCheck, // 导入校验
    importResult: importDownloadImportResult, // 导入结果下载
    importResultParams: { type: "sku_stock" },
    querForm: {
      platform_id: 67,
      type: "sku_stock", //导入类型
    },
    importApi: importImport,
  },
}

const DialogImportRef = ref()
const openDialogImport = (type) => {
  importConfig.value = importConfigOpt[type]

  nextTick(() => {
    DialogImportRef.value.open()
  })
}

// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
const batchVisible = ref(false)
const currentConfirm = ref({})
const batchOConfig = {
  // 供货价维护
  goodsPrice: {
    formOptions: { inline: true, labelPosition: "left" },
    width: 720,
    form: {},
    title: "修改供货价",
    api: updateGoodsPrice,
    fieldOptions: [
      {
        field: "goods_price",
        slot: "GoodsPrice",
      },
    ],
  },
  // 批量标记状态
  salesStatus: {
    formOptions: { inline: true, labelPosition: "left" },
    // width: 0,
    form: {},
    title: "批量标记状态",
    api: salesStatusUpdate,
    fieldOptions: [
      {
        label: "销售状态",
        field: "is_sales",
        type: "select",
        options: {
          placeholder: "销售状态",
          data: [
            { label: "在售", value: 1 },
            { label: "非在售", value: 0 },
          ],
        },
        style: { width: "380px" },
      },
    ],
  },
}
const openConfirmInput = (type, params) => {
  let rows = tableRef?.value?.$table?.getCheckboxRecords()
  if (!params) {
    if (!rows.length) {
      return ElMessage.warning("请至少选择1条数据进行操作！")
    }
  }
  let confirm = {}
  switch (type) {
    case "goodsPrice": // 供货价维护
      confirm = batchOConfig.goodsPrice
      confirm.form = {
        id: params.id,
        goods_price: params.goods_price.map((v) => ({ ...v, currency: v.currency || "USD" })),
        // goods_price: {
        //   ...params.goods_price?.[0],
        //   currency: params.goods_price?.[0].currency || "USD",
        // },
        // currency: params.currency ? params.currency : "USD",
      }
      break

    case "salesStatus": // 批量标记状态
      confirm = batchOConfig.salesStatus
      confirm.form = {
        goods_ids: rows.map((v) => v.id),
      }
      break
  }
  confirm.type = type
  currentConfirm.value = confirm
  batchVisible.value = true
}
const handleConfirmSubmit = (param) => {
  try {
    // console.log(param)
    let params = {}
    let requests = null
    let message = "保存成功！"
    switch (currentConfirm.value.type) {
      case "goodsPrice": // 供货价维护
        requests = currentConfirm.value.api
        params = currentConfirm.value.form
        params.goods_price = params.goods_price.map((v) => ({ ...v, goods_price: Number(v.goods_price || 0) }))
        let isPrice = params.goods_price.find((v) => !v.goods_price)
        console.log(params.goods_price)

        if (isPrice) {
          return ElMessage({ showClose: true, message: "供货价不能为0", type: "warning" })
        }

        break

      case "salesStatus": // 批量标记状态
        requests = currentConfirm.value.api
        params = currentConfirm.value.form
        break
    }
    requests(params).then((res) => {
      ElMessage.success(message || res.message)
      batchVisible.value = false
      nextTick(() => {
        currentConfirm.value = {}
        query()
      })
    })
  } catch (error) {}
}
// 弹窗 表格数据展示
import DialogTableInfo from "@/components/DialogTableInfo/index.vue"
// 弹窗 表格数据展示
const dialogTableInfoVisible = ref(false)
const tableInfoConfirm = ref({})
const dialogTabelInfoConfig = {
  inventory: {
    title: "本地仓库存",
    api: ownerInventory,
    tableOptions: {
      // border: false,
      height: "500",
      columns: [
        { field: "warehouse_name", title: "仓库名称" },
        { field: "wms_attribute_cn", title: "仓库属性", width: "100" },
        { field: "asin", title: "ASIN", width: "120" },
        { field: "owner_name", title: "货主", width: "180" },
        { field: "num", title: "可用库存", width: "90" },
        { field: "lock_num", title: "锁定库存", width: "90" },
        // { field: "transit_num", title: "在途库存", width: "90" },
      ],
    },
  },

  isCombination: {
    title: "组合SKU信息",
    api: warehouseInventoryList,
    info: {},
    infoColumn: [
      { label: "组合SKU", value: "sku" },
      { label: "组合自定义SKU", value: "custom_sku" },
      { label: "赛盒SKU", value: "i_robot_box_sku" },
    ],
    tableOptions: {
      height: "500",
      columns: [
        { field: "item_sku", title: "SKU" },
        { field: "custom_sku", title: "自定义SKU" },
        // { field: "custom_sku", title: "赛盒SKU" },
        { field: "lock_inventory", title: "数量" },
        { field: "inventory", title: "库存", link: true },
      ],
      data: [],
    },
  },
  // 601099650448369
}
const openTableInfo = async (e, params) => {
  console.log(e)
  switch (e) {
    case "inventory":
      tableInfoConfirm.value = dialogTabelInfoConfig.inventory
      let res = await tableInfoConfirm.value.api({ data: [{ sku: params.sku }] })
      let data = res.data?.[0]?.inventory
      tableInfoConfirm.value.tableOptions.data = data.filter((v) => "1,5".includes(v.wms_attribute))
      break

    case "isCombination": // 组合sku列表
      tableInfoConfirm.value = dialogTabelInfoConfig.isCombination
      tableInfoConfirm.value.info = params

      let param = {
        data: params.combination_list.map((v) => ({ item_sku: v.sku, warehouse_id: v.warehouse_id || "" })),
      }
      let inventoryList = (await tableInfoConfirm.value.api(param))?.data
      // console.log(inventoryList)

      inventoryList.forEach((v) => {
        params.combination_list.forEach((val) => {
          if (v.item_sku == val.sku) {
            v.lock_inventory = val.quantity
          }
        })
      })

      tableInfoConfirm.value.tableOptions.data = inventoryList
      // console.log(tableInfoConfirm.value)

      // const warehouseParams = item.assembles.map((items) => ({
      //   item_sku: items.sku,
      //   rowId: row.id,
      //   warehouse_id: row.warehouse_id || "",
      // }))

      // let assembles = item.assembles
      // let warehouseData = (await apiGetWarehouseInventoryList({ data: warehouseParams })).data
      // warehouseData.forEach((v) => {
      //   assembles.forEach((val) => {
      //     if (v.item_sku == val.sku) {
      //       val.inventory = v.inventory
      //     }
      //   })
      // })
      // assembleSkuSee.value.formData = {
      //   sku: item.sku,
      //   custom_sku: item.custom_sku,
      //   i_robot_box_sku: item.i_robot_box_sku,
      //   tableData: assembles,
      // }
      // assembleSkuSee.value.open()

      break
    default:
      break
  }
  dialogTableInfoVisible.value = true
}

const transitHeader = reactive([
  { title: "采购中", key: "purchase_processing_num", type: "" },
  { title: "本地仓库存", key: "xxxxxxx", type: "" },
  // { title: "FBA在途", key: "transit_count", type: "" },
])

const headerMemu = reactive({
  sales: [
    { title: "预估销量", key: "predict_sales_qty", type: "" },
    { title: "今天销量", key: "today_qty", type: "" },
    { title: "昨天销量", key: "yesterday_qty", type: "" },
    { title: "前天销量", key: "before_yesterday_qty", type: "" },
    { title: "上前销量", key: "prev_before_yesterday_qty", type: "" },
  ],
  qty: [
    { title: "一周销量", key: "one_week_qty", type: "" },
    { title: "两周销量", key: "tow_week_qty", type: "" },
    { title: "30天销量", key: "thirty_day_qty", type: "" },
    { title: "90天销量", key: "ninety_day_qty", type: "" },
  ],
  // nventory: [
  //   { title: "可用", key: "inventory_num", type: "" },
  //   { title: "锁定", key: "inventory_lock_num", type: "" },
  //   { title: "合计", key: "inventory_total", type: "" },
  //   { title: "不可售", key: "inventory_unsale_num", type: "" },
  //   { title: "售完天数", key: "predict_sales_day", type: "" },
  // ],
  time: [
    { title: "创建时间", key: "create_time", type: "" },
    { title: "上架时间", key: "platform_date", type: "" },
    { title: "更新时间", key: "update_time", type: "" },
    { title: "首次到达FBA时间", key: "receipt_goods_time", type: "" },
  ],
})

const tableSort = (item, value) => {
  let type = item.type == value ? "" : value
  for (const key in headerMemu) {
    headerMemu[key].forEach((item) => {
      item.type = ""
    })
  }
  // item.type = item.type == value ? "" : value
  item.type = type
  tableRef?.value.setFormField("isSort", true)
  query()
}
import action from "@/utils/action.js"
const handleCommand = (e) => {
  let condition = {}
  let checkRow = tableRef?.value?.$table?.getCheckboxRecords()
  if (checkRow?.length) {
    condition.id = checkRow.map((v) => v.id)
  } else {
    condition = tableRef?.value.getQueryForm()
    let { skuRange } = tableRef?.value.getForm()
    if (skuRange) {
      condition[skuRange.type] = skuRange?.value?.split("\n")?.filter((v) => !!v.trim())
    }
  }
  condition.last_day = e
  historySalesExport(condition).then((res) => {
    ElMessageBox.confirm("导出成功，是否跳转导出中心下载文件！", {
      confirmButtonText: "跳转",
      cancelButtonText: "取消",
    })
      .then(() => {
        action.setGlobalState({
          changeMicoTabsPath: {
            path: "/user/profile",
            type: "push",
          },
        })
      })
      .catch(() => {})
  })
}
// 预估销量
import { ClickOutside as vClickOutside } from "element-plus"
const popoverRef = ref()
const onClickOutside = () => {
  // console.log(12)
  // unref(popoverRef).popperRef?.delayHide?.()
}

import { parseTime } from "@/utils/ruoyi"
const salesQtyTable = ref([])
const salesQtyShow = async (row) => {
  let start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
  let datetime = [new Date(start.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((v) => parseTime(v, "{y}-{m}-{d}"))
  let params = {
    sku: row.sku,
    platform_sku: row.platform_sku,
    asin: row.asin,
    shop_id: row.shop_id,
    payment_date_start: datetime[0],
    payment_date_end: datetime[1],
  }
  const res = await historySalesVolume(params)
  res.data.forEach((item) => {
    let day = getDayOfWeek(item.payment_date)
    item.day = `${item.payment_date?.slice(5)} (${day})`
  })
  res.data = res.data.reverse()
  salesQtyTable.value = res.data
}

const getDayOfWeek = (date) => {
  const days = ["日", "一", "二", "三", "四", "五", "六"]
  const dayNumber = new Date(date).getDay()
  return days[dayNumber]
}

// console.log(getDayOfWeek()) // 输出例如 "星期三"

import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"

import XForm from "@/components/XForm/index.vue"
import SelectProductCategories from "./components/ProductCategories/index.vue"

import VLog from "@/components/VLog"
const logRef = ref()

import DerivedCenter from "@/components/DerivedCenter"

// 导出中心
const DerivedCenterRef = ref()
const importHandleClick = async () => {
  let condition = {}
  let checkRow = tableRef?.value?.$table?.getCheckboxRecords()
  if (checkRow?.length) {
    condition.id = checkRow.map((v) => v.id)
  } else {
    condition = tableRef?.value.getQueryForm()
    let { skuRange } = tableRef?.value.getForm()
    if (skuRange) {
      condition[skuRange.type] = skuRange?.value?.split("\n")?.filter((v) => !!v.trim())
    }
  }
  condition.platform_id = 67
  let parmas = {
    module: "temu_listing_list_export",
    tag_name: "temu_listing_list_export",
    exportName: "TEMU刊登listing导出",
    condition,
  }
  DerivedCenterRef.value.open(parmas)
}

const downloadUrl = ref("")

const tableRef = ref()

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}

// 查询
const query = () => {
  tableRef?.value.query()
}
// 枚举 数据
const originOption = ref({
  // transportationOpt: [
  //   { label: "快递", value: 10 },
  //   { label: "空运", value: 11 },
  //   { label: "快海运", value: 12 },
  //   { label: "慢海运(海卡)", value: 13 },
  //   { label: "铁运", value: 14 },
  //   { label: "卡航", value: 15 },
  //   { label: "邮政小包", value: 16 },
  //   { label: "专线小包", value: 17 },
  //   { label: "其他", value: 18 },
  // ],
})

const formshow = ref(false)
//获取下拉数据
onMounted(() => {
  getOption()
})

import { apiGetPlatformSites, getShop } from "@/api/amazon"
const getOption = async () => {
  const shopRes = await getShop({ platform_ids: [67] })
  originOption.value.temuShopOpt = shopRes.data.map((n) => ({ label: n.shop_name, value: n.shop_id }))

  let temuSitesOpt = await siteCountryList({ platform_id: 67 })
  originOption.value.temuSitesOpt = temuSitesOpt?.data?.map((n) => ({ label: n.site_name, value: n.site_id }))

  const currency = await getCurrency()
  originOption.value.currency = currency.data

  formshow.value = true
}

const formOption = ref({
  inline: true,
})

import {
  fieldList, // 搜索条件 配置
} from "./config.jsx"

const salesTagColor = {
  草稿: "bg-[#E5F6F1] text-[#00AC76]",
  刊登中: "bg-[#E50113]  text-[red]",
  已下架: "bg-[#E6E7E9] text-[#9DA1AD]",
  刊登失败: "bg-[#FCE5E7] text-[#E50113]",
  售完: "bg-[#EBECEE] text-[#333]",
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    save: "publish/amazon/list", // 必填，唯一
    data: {
      isSort: false,
      activity_status: "",
      site_id: "",
      status: "",
      is_requires_stocking: "",
      skuRange: { type: "sku", value: "" },
      userRange: { type: "operator_user", value: "" },
      timeRange: { type: "platform_date", value: [] },
      sku_stock_qty: { min: null, max: null },
    },
  },

  rowConfig: { height: "162" },
  showOverflow: false,
  columns: [
    { type: "checkbox", fixed: "left", width: 40 },
    { field: "id", title: "草稿编号", width: 80 },

    {
      title: "产品信息",
      width: 300,
      slots: {
        default: ({ row }) => (
          <div class="flex items-center">
            <div class="w-[100px] h-[100px]">
              <el-image style="width:100px;height:100px" src={row.attr_img || ""} />
            </div>
            <div class="ml-[4px] flex-1 " style="width: calc(100% - 104px)">
              {row.is_sales ? <span class="base-tag-primary ">在售</span> : ""}

              <VText title="商品SPU ID" value={row.product_id} line={1} copy />
              <VText title="货品SKU ID" value={row.product_sku_id} line={1} copy />
              <VText title="货品SKC ID" value={row.product_skc_id} copy line={1} />
              <VText title="Asin" value={row.asin} line={1} type="link" onClick={() => window.open(row.asin_url, "_blank")} copy />
              <VText title="分类" value={row.spu_category_text} line={1} />
            </div>
          </div>
        ),
      },
    },

    {
      title: "产品描述",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div class="flex items-center">
            <VText value={row.product_name} line={3} />
          </div>
        ),
      },
    },

    {
      title: "SKU信息",
      width: 300,
      slots: {
        default: ({ row }) => (
          <div class="">
            <div class="flex items-center">
              <div>
                <VText title="SKU" value={row.sku || "点击关联"} line={1} copy type="link" onClick={() => openRelateSku(row)} />
              </div>

              {row.is_combination ? (
                <div class="text-red cursor-pointer" onClick={() => openTableInfo("isCombination", row)}>
                  组合
                </div>
              ) : (
                ""
              )}
            </div>

            <VText title="渠道SKU" value={row.platform_sku} line={1} copy />
            <VText title="SKU货号" value={row.sku_code} line={1} copy />

            <div class="flex">
              <div class="text-[var(--base-sub-text-color)]">属性：</div>
              <div>
                {row.sku_spec.map((v, i) => (
                  <VText value={v} line={1} />
                ))}
              </div>
            </div>
          </div>
        ),
      },
    },

    {
      title: "账号/站点/销售",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <img src={flag[row.site]} alt="" class="w-[46px] mr-[8px]" />
              <VText value={row.site} line={1} />
            </div>
            <VText title="账号" value={row.shop_name} line={1} copy />
            <VText title="平台站点" value={row.bind_site_name} line={1} />
            <VText title="销售人员" value={row.operations_personnel} line={1} />
            <VText title="开发人员" value={row.develop_id_text} line={1} />
            <VText title="销售部门" value={row.operations_department} line={1} />
          </div>
        ),
      },
    },

    {
      title: "供货价/可发货库存/链接可售数量",
      width: 240,
      slots: {
        header: ({}) => (
          <div>
            <div>供货价</div>
            <div>可发货库存</div>
            <div>链接可售数量</div>
          </div>
        ),

        default: ({ row }) => {
          const slot = {
            reference: () => <VText title="链接可售数量" value={row.sku_stock_qty} line={1} class={row.sku_stock_qty > row.local_inventory_num ? "text-red" : ""} />,
          }
          //  <VText title="供货价" value={`${row?.goods_price?.[0]?.goods_price || "-"} ${row?.currency || ""}`} line={1} />
          return (
            <div>
              <div class="flex">
                <div>
                  <VText title="供货价" value={`${row?.goods_price_show || "-"} ${row?.currency || ""}`} line={1} />
                </div>

                <div class="flex-1 ml-[8px]">
                  <svg-icon icon-class="edit" class="text-[14px] text-[#3487FF] cursor-pointer" onClick={() => openConfirmInput("goodsPrice", row)} />
                </div>
              </div>

              <VText title="可发货库存" class="cursor-pointer" value={row.local_inventory_num} line={1} onClick={() => AssembleSkuSeeRef.value.open(row)} type="link" />

              <div class="flex items-center">
                <div>
                  <el-popover placement="top-start" width={300} trigger="hover" v-slots={slot}>
                    <el-table data={row?.sku_stock_list}>
                      <el-table-column prop="warehouseName" label="仓库" width="180" />
                      <el-table-column prop="skuStockQuantity" label="数量" />
                    </el-table>
                  </el-popover>
                </div>
                <div class=" ml-[8px]">
                  <svg-icon icon-class="edit" class="text-[14px] text-[#3487FF] cursor-pointer" onClick={() => openSkuDtockRef(row)} />
                </div>
                <div class="flex-1 ml-[8px]">
                  {row.is_abnormal_inventory == 1 ? (
                    <el-tooltip effect="dark" content="库存异常<br/>链接可售数量高于可发货库存" placement="top-start" raw-content={true}>
                      <div class="dk-iconfont icon-WarnTriangleFilled text-yellow"></div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                </div>
              </div>
            </div>
          )
        },
      },
    },

    {
      title: "近期销量",
      width: 140,
      field: "sales",
      slots: {
        default: "Sales",
        header: "soltHeader",
      },
    },
    {
      title: "销量统计",
      width: 150,
      field: "qty",
      slots: {
        header: "soltHeader",
        default: ({ row }) => (
          <div>
            <VText title="一周" value={row.one_week_qty} line={1} class="text-green font-bold" />
            <VText title="两周" value={row.tow_week_qty} line={1} class="text-yellow font-bold" />
            <VText title="30天" value={row.thirty_day_qty} line={1} class="text-red font-bold" />
            <VText title="90天" value={row.ninety_day_qty} line={1} class="text-red font-bold" />
          </div>
        ),
      },
    },

    {
      title: "时间/日志",
      width: 240,
      field: "time",
      slots: {
        header: "soltHeader",
        default: ({ row }) => (
          <div>
            <VText title="更新时间" value={row.update_time} line={1} />
            <VText title="上架时间" value={row.platform_date} line={1} />
            <div class="flex items-center cursor-pointer text-[#3487ff]" onClick={() => logRef?.value.open({ business_id: row.id, tag: "goods" })}>
              <svg-icon icon-class="baobiao" class=" text-[18px] mr-[2px]" />
              日志
            </div>
          </div>
        ),
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        let params = { ...form, ...page }
        params = initForm(params)
        // let res = await queryList(params)
        // res.data[0].sku_spec = [...res.data[0].sku_spec, ...res.data[0].sku_spec, ...res.data[0].sku_spec]
        return await queryList(params)
      },
    },
  },
})
const queryList = (params) => {
  return new Promise((resolve, reject) => {
    amazonListingList(params).then((res) => {
      res.data?.forEach((item) => {
        let name = item.operations_department?.split("/")
        name?.shift()
        name?.shift()
        item.operations_department = name?.join("/")
      })
      tableRef?.value?.$table.reloadData([])
      res.data.forEach((item) => {
        item.goods_price_show = item.goods_price?.[0].goods_price
        if (item.goods_price.length > 1) {
          const maxItem = item.goods_price.reduce((prev, current) => (Number(prev.goods_price) > Number(current.goods_price) ? prev : current))
          const minItem = item.goods_price.reduce((prev, current) => (Number(prev.goods_price) < Number(current.goods_price) ? prev : current))
          if (minItem.goods_price != maxItem.goods_price) {
            item.goods_price_show = `${minItem.goods_price} - ${maxItem.goods_price}`
          }
        }
      })
      resolve(res)
    })
  })
}
const initForm = (params) => {
  let { isSort, skuRange } = tableRef?.value.getForm()

  if (!isSort) {
    for (const key in headerMemu) {
      headerMemu[key].forEach((item) => {
        item.type = ""
      })
    }
    headerMemu.sales[1].type = "desc"
    isSort = true
  }
  if (isSort) {
    let sort = [...Object.values(headerMemu).flat(), ...Object.values(transitHeader).flat()]
    sort = sort.filter((v) => v.type).map((v) => ({ field: v.key, type: v.type }))
    params.sort = sort
  }
  params[skuRange.type] = skuRange?.value
    ?.split("\n")
    ?.filter((v) => !!v.trim())
    .map((v) => v.trim())

  if (params.sku_stock_qty) {
    params.sku_stock_qty_min = params.sku_stock_qty.min
    params.sku_stock_qty_max = params.sku_stock_qty.max
    delete params.sku_stock_qty
  }
  params.sku_cn_title = params.sku_cn_title?.trim()
  params.platform_id = 67
  return params
}
</script>
<style lang="scss" scoped>
:deep(.view-table) {
  // .status-tag {
  //   width: 30px;
  //   height: 14px;
  //   line-height: 14px;
  //   text-align: center;
  //   border-radius: 2px;
  //   font-size: 10px;
  //   background: #eaf3ff;
  //   color: #3487ff;
  // }
  .bold-text {
    font-weight: bold;
    color: #3487ff;
    cursor: pointer;
  }
  .text-666 {
    * {
      color: #666;
    }
  }
  .text-333 {
    * {
      color: #333;
    }
  }
  .zhandian-icon {
    width: 64px;
    height: 32px;
    margin-right: 8px;
    &.jp {
      border: 1px solid #333;
    }
  }
}

.day-table {
  border-top: 1px solid #eff3fe;
  border-left: 1px solid #eff3fe;
  * {
    line-height: 48px;
    text-align: center;
    border-bottom: 1px solid #eff3fe;
    border-right: 1px solid #eff3fe;
  }
  .header {
    background: #f6faff;
  }
  .value {
    color: #3487ff;
  }
}
</style>
